﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using Grain.Crm.ExcelExtractor.InputDescription;
using Grain.Crm.ExcelImporter;

namespace Grain.Crm.ExcelExtractor
{
    public class XlsValueRetriever
    {
        public static string GetValueByDescription(EnumerableRowCollection<DataRow> collection, ValueDescription description, int startAtRow)
        {
            var value = collection.GetValue(description.Row + startAtRow, description.Column);

            if (string.IsNullOrEmpty(value))
                return value;

            if (!string.IsNullOrEmpty(value) && description.IsNumber)
            {
                double number;
                var isParsed = double.TryParse(value.Replace(" ", ""), NumberStyles.Number, new CultureInfo(ValueDescription.SheetCulture), out number);

                if (isParsed)
                    return number.ToString(new CultureInfo(""));
                else
                    throw new FormatException(
                        "The value couldn't be parsed as number. XlsField: "
                        + description.XlsDescription + ". Value: '" + value
                        + "'. Culture used: " + ValueDescription.SheetCulture);
            }
            else if (!string.IsNullOrEmpty(value) && description.ParseDateAs == DateFormat.DaysSince1900)
            {
                return DateTime.FromOADate(double.Parse(value)).ToString(CultureInfo.InvariantCulture);
            }
            else if (!string.IsNullOrEmpty(value) && description.ParseDateAs == DateFormat.Slovak)
            {

                var date = DateTime.Parse(value, new CultureInfo("sk-SK"));
                return date.ToString(CultureInfo.InvariantCulture);

            }
            else if (!string.IsNullOrEmpty(value) && description.ParseDateAs == DateFormat.English)
            {
                var numDate = int.Parse(value);
                var parsedDate = DateTime.MinValue.AddDays(numDate);

                var date = DateTime.Parse(value, new CultureInfo("en-US"));
                return date.ToString(CultureInfo.InvariantCulture);

            }
            else
            {
                value = value.Replace(',', ';'); //avoid using the comma-separator because it is also separator for values in input-row

            }

            return value;
        }

        /// <summary>
        /// Gets the value from xlt-parsed collection. 
        /// If number is to retrieve, it parses it according to current culture and returns it as culture-invariant string.
        /// </summary>
        public static string GetValueByDescription(EnumerableRowCollection<DataRow> collection, ValueDescription description)
        {
            return GetValueByDescription(collection, description, 0);
        }
    }
}
